예제 #1
0
class Config:
    def __init__(self):
        self.badges = Badges()
        self.local_storage = LocalStorage()

        self.base_path = '/opt/hsf/'
        self.config_path = self.base_path + 'config/'

        self.db_config_file = self.config_path + 'db_config.yml'
        self.path_config_file = self.config_path + 'path_config.yml'
        self.core_config_file = self.config_path + 'core_config.yml'

        self.db_config = self.local_storage.get("db_config")
        self.path_config = self.local_storage.get("path_config")
        self.core_config = self.local_storage.get("core_config")

    @staticmethod
    def get_config_file(content):
        return yaml.safe_load(content)

    def configure(self):
        db_config = self.get_config_file(open(self.db_config_file))
        path_config = self.get_config_file(open(self.path_config_file))
        core_config = self.get_config_file(open(self.core_config_file))

        self.db_config = db_config
        self.path_config = path_config
        self.core_config = core_config

        self.local_storage.set("db_config", self.db_config)
        self.local_storage.set("path_config", self.path_config)
        self.local_storage.set("core_config", self.core_config)

        self.global_storage = GlobalStorage(
            self.path_config['base_paths']['storage_path'])
        self.global_storage.set_all()
예제 #2
0
class IO:
    def __init__(self):
        self.colors = Colors()
        self.local_storage = LocalStorage()
        self.fmt = FMT()

    def output(self, message, start='\033[1K\r', end='\n'):
        sys.stdout.write(start + message + end)
        sys.stdout.flush()
        if self.local_storage.get("current_prompt") and self.local_storage.get("active_input"):
            prompt = start + self.local_storage.get("current_prompt") + readline.get_line_buffer()
            sys.stdout.write(prompt)
            sys.stdout.flush()

    def input(self, prompt_message):
        self.local_storage.set("current_prompt", prompt_message)
        self.local_storage.set("active_input", True)
        commands = input(self.colors.REMOVE + prompt_message)
        commands = self.fmt.format_commands(commands)
        arguments = list()
        if commands:
            arguments = commands[1:]
        self.local_storage.set("active_input", False)
        return commands, arguments
예제 #3
0
class Payloads:
    def __init__(self):
        self.importer = Importer()
        self.local_storage = LocalStorage()
        self.badges = Badges()

    def check_exist(self, name):
        if self.check_style(name):
            all_payloads = self.local_storage.get("payloads")
            if all_payloads:
                for database in all_payloads.keys():
                    payloads = all_payloads[database]

                    platform = self.get_platform(name)
                    architecture = self.get_architecture(name)

                    if platform in payloads.keys():
                        if architecture in payloads[platform].keys():
                            payload = self.get_name(name)
                            if payload in payloads[platform][
                                    architecture].keys():
                                return True
        return False

    @staticmethod
    def check_style(name):
        if len(name.split('/')) >= 3:
            return True
        return False

    def get_platform(self, name):
        if self.check_style(name):
            return name.split('/')[0]
        return None

    def get_architecture(self, name):
        if self.check_style(name):
            return name.split('/')[1]
        return None

    def get_name(self, name):
        if self.check_style(name):
            return os.path.join(*(name.split(os.path.sep)[2:]))
        return None

    def get_payload_object(self, platform, architecture, name):
        payload_full_name = self.get_full_name(platform, architecture, name)
        if self.check_exist(payload_full_name):
            database = self.get_database(payload_full_name)
            return self.local_storage.get(
                "payloads")[database][platform][architecture][name]
        return None

    def get_database(self, name):
        if self.check_style(name):
            all_payloads = self.local_storage.get("payloads")
            if all_payloads:
                for database in all_payloads.keys():
                    payloads = all_payloads[database]

                    platform = self.get_platform(name)
                    architecture = self.get_architecture(name)

                    if platform in payloads.keys():
                        if architecture in payloads[platform].keys():
                            payload = self.get_name(name)
                            if payload in payloads[platform][
                                    architecture].keys():
                                return database
        return None

    @staticmethod
    def get_full_name(platform, architecture, name):
        return platform + '/' + architecture + '/' + name

    def check_current_module(self):
        if self.local_storage.get("current_module"):
            if len(self.local_storage.get("current_module")) > 0:
                return True
        return False

    def get_current_module_object(self):
        if self.check_current_module():
            return self.local_storage.get_array(
                "current_module",
                self.local_storage.get("current_module_number"))
        return None

    def get_current_module_name(self):
        if self.check_current_module():
            return self.local_storage.get_array(
                "current_module",
                self.local_storage.get(
                    "current_module_number")).details['Module']
        return None

    def import_payload(self, module_name, platform, architecture, name):
        payloads = self.get_payload_object(platform, architecture, name)
        try:
            payload_object = self.importer.import_payload(payloads['Path'])
            current_module_name = module_name

            imported_payloads = self.local_storage.get("imported_payloads")
            if imported_payloads:
                if current_module_name in imported_payloads.keys():
                    imported_payloads[current_module_name].update({
                        payload_object.details['Payload']:
                        copy.copy(payload_object)
                    })
                else:
                    imported_payloads.update({
                        current_module_name: {
                            payload_object.details['Payload']:
                            copy.copy(payload_object)
                        }
                    })
            else:
                imported_payloads = {
                    current_module_name: {
                        payload_object.details['Payload']:
                        copy.copy(payload_object)
                    }
                }
            self.local_storage.set("imported_payloads", imported_payloads)
        except Exception:
            return None
        return payload_object

    def check_imported(self, module_name, name):
        imported_payloads = self.local_storage.get("imported_payloads")
        current_module_name = module_name

        if imported_payloads:
            if current_module_name in imported_payloads.keys():
                if name in imported_payloads[current_module_name].keys():
                    return True
        return False

    def get_current_payload(self):
        imported_payloads = self.local_storage.get("imported_payloads")
        current_module_object = self.get_current_module_object()
        current_module_name = current_module_object.details['Module']

        if hasattr(current_module_object, "payload"):
            name = current_module_object.payload['Value']
            if current_module_name in imported_payloads.keys():
                if name in imported_payloads[current_module_name].keys():
                    return imported_payloads[current_module_name][name]
        return None

    def add_payload(self, module_name, platform, architecture, name):
        payloads = self.get_payload_object(platform, architecture, name)

        not_installed = list()
        for dependence in payloads['Dependencies']:
            if not self.importer.import_check(dependence):
                not_installed.append(dependence)
        if not not_installed:
            full_name = self.get_full_name(platform, architecture, name)

            if not self.check_imported(module_name, full_name):
                payload_object = self.import_payload(module_name, platform,
                                                     architecture, name)
                if not payload_object:
                    self.badges.output_error(
                        "Failed to select payload from database!")
                    return False
        else:
            self.badges.output_error(
                "Payload depends this dependencies which is not installed:")
            for dependence in not_installed:
                self.badges.output_empty("    * " + dependence)
            return False
        return True
예제 #4
0
class DB:
    def __init__(self):
        self.badges = Badges()
        self.local_storage = LocalStorage()

    def disconnect_payloads_database(self, name):
        if self.local_storage.get("connected_payloads_databases"):
            if name in self.local_storage.get("connected_payloads_databases"):
                self.local_storage.delete_element(
                    "connected_payloads_databases", name)
                self.local_storage.delete_element("payloads", name)
                return
        self.badges.output_error("No such payloads database connected!")

    def disconnect_modules_database(self, name):
        if self.local_storage.get("connected_modules_databases"):
            if name in self.local_storage.get("connected_modules_databases"):
                self.local_storage.delete_element(
                    "connected_modules_databases", name)
                self.local_storage.delete_element("modules", name)
                return
        self.badges.output_error("No such modules database connected!")

    def disconnect_plugins_database(self, name):
        if self.local_storage.get("connected_plugins_databases"):
            if name in self.local_storage.get("connected_plugins_databases"):
                self.local_storage.delete_element(
                    "connected_plugins_databases", name)
                self.local_storage.delete_element("plugins", name)
                return
        self.badges.output_error("No such plugins database connected!")

    def connect_payloads_database(self, name, path):
        if self.local_storage.get("connected_payloads_databases"):
            if name in self.local_storage.get("connected_payloads_databases"):
                self.bagdes.output_error(
                    "Payloads database already connected!")
                return
        if not os.path.exists(path) or not str.endswith(path, "json"):
            self.badges.output_error("Not a payloads database!")
            return

        try:
            database = json.load(open(path))
        except Exception:
            self.badges.output_error("Failed to connect payloads database!")
            return

        if '__database__' not in database.keys():
            self.badges.output_error("No __database__ section found!")
            return
        if database['__database__']['type'] != "payloads":
            self.badges.output_error("Not a payloads database!")
            return
        del database['__database__']

        payloads = {name: database}

        data = {name: {'path': path}}
        if not self.local_storage.get("connected_payloads_databases"):
            self.local_storage.set("connected_payloads_databases", dict())
        self.local_storage.update("connected_payloads_databases", data)

        if self.local_storage.get("payloads"):
            self.local_storage.update("payloads", payloads)
        else:
            self.local_storage.set("payloads", payloads)

    def connect_modules_database(self, name, path):
        if self.local_storage.get("connected_modules_databases"):
            if name in self.local_storage.get("connected_modules_databases"):
                self.bagdes.output_error("Modules database already connected!")
                return
        if not os.path.exists(path) or not str.endswith(path, "json"):
            self.badges.output_error("Not a modules database!")
            return

        try:
            database = json.load(open(path))
        except Exception:
            self.badges.output_error("Failed to connect modules database!")
            return

        if '__database__' not in database.keys():
            self.badges.output_error("No __database__ section found!")
            return
        if database['__database__']['type'] != "modules":
            self.badges.output_error("Not a modules database!")
            return
        del database['__database__']

        modules = {name: database}

        data = {name: {'path': path}}
        if not self.local_storage.get("connected_modules_databases"):
            self.local_storage.set("connected_modules_databases", dict())
        self.local_storage.update("connected_modules_databases", data)

        if self.local_storage.get("modules"):
            self.local_storage.update("modules", modules)
        else:
            self.local_storage.set("modules", modules)

    def connect_plugins_database(self, name, path):
        if self.local_storage.get("connected_plugins_databases"):
            if name in self.local_storage.get("connected_plugins_databases"):
                self.bagdes.output_error("Plugins database already connected!")
                return
        if not os.path.exists(path) or not str.endswith(path, "json"):
            self.badges.output_error("Not a database!")
            return

        try:
            database = json.load(open(path))
        except Exception:
            self.badges.output_error("Failed to connect plugins database!")
            return

        if '__database__' not in database.keys():
            self.badges.output_error("No __database__ section found!")
            return
        if database['__database__']['type'] != "plugins":
            self.badges.output_error("Not a plugins database!")
            return
        del database['__database__']

        plugins = {name: database}

        data = {name: {'path': path}}
        if not self.local_storage.get("connected_plugins_databases"):
            self.local_storage.set("connected_plugins_databases", dict())
        self.local_storage.update("connected_plugins_databases", data)

        if self.local_storage.get("plugins"):
            self.local_storage.update("plugins", plugins)
        else:
            self.local_storage.set("plugins", plugins)
예제 #5
0
class Sessions:
    def __init__(self):
        self.badges = Badges()
        self.local_storage = LocalStorage()

    def add_session(self, session_platform, session_type, session_host,
                    session_port, session_object):
        if not self.local_storage.get("sessions"):
            self.local_storage.set("sessions", dict())

        session_id = 0
        if session_platform in self.local_storage.get("sessions").keys():
            sessions = self.local_storage.get("sessions")
            session_id = len(sessions[session_platform])
            sessions[session_platform][int(session_id)] = {
                'type': session_type,
                'host': session_host,
                'port': session_port,
                'object': session_object
            }
        else:
            sessions = {
                session_platform: {
                    int(session_id): {
                        'type': session_type,
                        'host': session_host,
                        'port': session_port,
                        'object': session_object
                    }
                }
            }

        self.local_storage.update("sessions", sessions)
        return session_id

    def check_session_exist(self, session_platform, session_id):
        sessions = self.local_storage.get("sessions")
        if sessions:
            if session_platform in sessions.keys():
                if int(session_id) in sessions[session_platform].keys():
                    return True
        return False

    def spawn_interactive_connection(self, session_platform, session_id):
        sessions = self.local_storage.get("sessions")
        if self.check_session_exist(session_platform, session_id):
            self.badges.output_process("Interacting with session " +
                                       str(session_id) + "...")
            self.badges.output_success("Interactive connection spawned!")
            self.badges.output_information("Type commands below.\n")

            sessions[session_platform][int(session_id)]['object'].interact()
        else:
            self.badges.output_error("Invalid session given!")

    def close_session(self, session_platform, session_id):
        sessions = self.local_storage.get("sessions")
        if self.check_session_exist(session_platform, session_id):
            try:
                sessions[session_platform][int(session_id)]['object'].close()
                del sessions[session_platform][int(session_id)]

                if not sessions[session_platform]:
                    del sessions[session_platform]
                self.local_storage.update("sessions", sessions)
            except Exception:
                self.badges.output_error("Failed to close session!")
        else:
            self.badges.output_error("Invalid session given!")

    def get_session(self, session_platform, session_type, session_id):
        sessions = self.local_storage.get("sessions")
        if self.check_session_exist(session_platform, session_id):
            if session_type == sessions[session_platform][int(
                    session_id)]['type']:
                return sessions[session_platform][int(session_id)]['object']
            self.badges.output_error("Session with invalid type!")
            return None
        return None
예제 #6
0
class Modules:
    def __init__(self):
        self.types = Types()
        self.badges = Badges()
        self.sessions = Sessions()
        self.payloads = Payloads()
        self.local_storage = LocalStorage()
        self.importer = Importer()

    def check_exist(self, name):
        if self.check_style(name):
            all_modules = self.local_storage.get("modules")
            if all_modules:
                for database in all_modules.keys():
                    modules = all_modules[database]

                    category = self.get_category(name)
                    platform = self.get_platform(name)

                    if category in modules.keys():
                        if platform in modules[category].keys():
                            module = self.get_name(name)
                            if module in modules[category][platform].keys():
                                return True
        return False

    def check_imported(self, name):
        imported_modules = self.local_storage.get("imported_modules")
        if imported_modules:
            if name in imported_modules.keys():
                return True
        return False

    @staticmethod
    def check_style(name):
        if len(name.split('/')) >= 3:
            return True
        return False

    def check_current_module(self):
        if self.local_storage.get("current_module"):
            if len(self.local_storage.get("current_module")) > 0:
                return True
        return False

    def get_module_object(self, category, platform, name):
        module_full_name = self.get_full_name(category, platform, name)
        if self.check_exist(module_full_name):
            database = self.get_database(module_full_name)
            return self.local_storage.get(
                "modules")[database][category][platform][name]
        return None

    def get_current_module_object(self):
        if self.check_current_module():
            return self.local_storage.get_array(
                "current_module",
                self.local_storage.get("current_module_number"))
        return None

    def get_current_module_platform(self):
        if self.check_current_module():
            return self.local_storage.get_array(
                "current_module",
                self.local_storage.get(
                    "current_module_number")).details['Platform']
        return None

    def get_current_module_name(self):
        if self.check_current_module():
            return self.local_storage.get_array(
                "current_module",
                self.local_storage.get(
                    "current_module_number")).details['Module']
        return None

    def get_database(self, name):
        if self.check_style(name):
            all_modules = self.local_storage.get("modules")
            if all_modules:
                for database in all_modules.keys():
                    modules = all_modules[database]

                    category = self.get_category(name)
                    platform = self.get_platform(name)

                    if category in modules.keys():
                        if platform in modules[category].keys():
                            module = self.get_name(name)
                            if module in modules[category][platform].keys():
                                return database
        return None

    def get_category(self, name):
        if self.check_style(name):
            return name.split('/')[0]
        return None

    def get_platform(self, name):
        if self.check_style(name):
            return name.split('/')[1]
        return None

    def get_name(self, name):
        if self.check_style(name):
            return os.path.join(*(name.split(os.path.sep)[2:]))
        return None

    @staticmethod
    def get_full_name(category, platform, name):
        return category + '/' + platform + '/' + name

    def compare_types(self, value_type, value):
        if value_type and not value_type.lower == 'all':
            if value_type.lower() == 'mac':
                if not self.types.is_mac(value):
                    self.badges.output_error(
                        "Invalid value, expected valid MAC!")
                    return False

            if value_type.lower() == 'ip':
                if not self.types.is_ip(value):
                    self.badges.output_error(
                        "Invalid value, expected valid IP!")
                    return False

            if value_type.lower() == 'ipv4':
                if not self.types.is_ipv4(value):
                    self.badges.output_error(
                        "Invalid value, expected valid IPv4!")
                    return False

            if value_type.lower() == 'ipv6':
                if not self.types.is_ipv6(value):
                    self.badges.output_error(
                        "Invalid value, expected valid IPv6!")
                    return False

            if value_type.lower() == 'ipv4_range':
                if not self.types.is_ipv4_range(value):
                    self.badges.output_error(
                        "Invalid value, expected valid IPv4 range!")
                    return False

            if value_type.lower() == 'ipv6_range':
                if not self.types.is_ipv6_range(value):
                    self.badges.output_error(
                        "Invalid value, expected valid IPv6 range!")
                    return False

            if value_type.lower() == 'port':
                if not self.types.is_port(value):
                    self.badges.output_error(
                        "Invalid value, expected valid port!")
                    return False

            if value_type.lower() == 'port_range':
                if not self.types.is_port_range(value):
                    self.badges.output_error(
                        "Invalid value, expected valid port range!")
                    return False

            if value_type.lower() == 'number':
                if not self.types.is_number(value):
                    self.badges.output_error(
                        "Invalid value, expected valid number!")
                    return False

            if value_type.lower() == 'integer':
                if not self.types.is_integer(value):
                    self.badges.output_error(
                        "Invalid value, expected valid integer!")
                    return False

            if value_type.lower() == 'float':
                if not self.types.is_float(value):
                    self.badges.output_error(
                        "Invalid value, expected valid float!")
                    return False

            if value_type.lower() == 'boolean':
                if not self.types.is_boolean(value):
                    self.badges.output_error(
                        "Invalid value, expected valid boolean!")
                    return False

            if value_type.lower() == 'session':
                module_platform = self.get_current_module_platform()
                if not self.sessions.check_exist(module_platform, value):
                    return False
        return True

    def set_current_module_option(self, option, value):
        if self.check_current_module():
            current_module = self.get_current_module_object()

            if not hasattr(current_module, "options") and not hasattr(
                    current_module, "payload"):
                self.badges.output_warning("Module has no options.")
                return

            if hasattr(current_module,
                       "payload") and option.lower() == "payload":
                if self.payloads.check_exist(value):
                    module_name = self.get_current_module_name()

                    platform = self.payloads.get_platform(value)
                    architecture = self.payloads.get_architecture(value)
                    name = self.payloads.get_name(value)

                    payload = self.payloads.get_payload_object(
                        platform, architecture, name)
                    module_payload = current_module.payload

                    valid = 0
                    if module_payload['Types'] is None or payload[
                            'Type'] in module_payload['Types']:
                        valid += 1
                    if module_payload['Categories'] is None or payload[
                            'Category'] in module_payload['Categories']:
                        valid += 1
                    if module_payload['Platforms'] is None or payload[
                            'Platform'] in module_payload['Platforms']:
                        valid += 1
                    if module_payload['Architectures'] is None or payload[
                            'Architecture'] in module_payload['Architectures']:
                        valid += 1

                    if valid == 4:
                        if not self.payloads.add_payload(
                                module_name, platform, architecture, name):
                            self.badges.output_error(
                                "Invalid payload, expected valid payload!")
                            return
                        self.badges.output_information(option + " ==> " +
                                                       value)
                        self.local_storage.set_module_payload(
                            "current_module",
                            self.local_storage.get("current_module_number"),
                            value)
                        return
                    self.badges.output_error(
                        "Incompatible payload type, category or platform!")
                    return
                self.badges.output_error(
                    "Invalid payload, expected valid payload!")
                return

            if hasattr(current_module, "options"):
                if option in current_module.options.keys():
                    value_type = current_module.options[option]['Type']

                    if self.compare_types(value_type, value):
                        self.badges.output_information(option + " ==> " +
                                                       value)
                        self.local_storage.set_module_option(
                            "current_module",
                            self.local_storage.get("current_module_number"),
                            option, value)
                    return

            if hasattr(current_module, "payload"):
                current_payload = self.payloads.get_current_payload()
                if current_payload and hasattr(current_payload, "options"):
                    if option in current_payload.options.keys():
                        value_type = current_payload.options[option]['Type']

                        if self.compare_types(value_type, value):
                            self.badges.output_information(option + " ==> " +
                                                           value)
                            self.local_storage.set_payload_option(
                                current_module.details['Module'],
                                current_payload.details['Payload'], option,
                                value)
                    else:
                        self.badges.output_error("Unrecognized option!")
                else:
                    self.badges.output_error("Unrecognized option!")
        else:
            self.badges.output_warning("No module selected.")

    def import_module(self, category, platform, name):
        modules = self.get_module_object(category, platform, name)
        try:
            module_object = self.importer.import_module(modules['Path'])
            if not self.local_storage.get("imported_modules"):
                self.local_storage.set("imported_modules", dict())
            self.local_storage.update(
                "imported_modules",
                {self.get_full_name(category, platform, name): module_object})
        except Exception:
            return None
        return module_object

    def add_module(self, category, platform, name):
        modules = self.get_module_object(category, platform, name)

        not_installed = list()
        for dependence in modules['Dependencies']:
            if not self.importer.import_check(dependence):
                not_installed.append(dependence)
        if not not_installed:
            imported_modules = self.local_storage.get("imported_modules")
            full_name = self.get_full_name(category, platform, name)

            if self.check_imported(full_name):
                module_object = imported_modules[full_name]
                self.add_to_global(module_object)
            else:
                module_object = self.import_module(category, platform, name)
                if module_object:
                    if hasattr(module_object, "payload"):
                        payload_name = module_object.payload['Value']

                        platform = self.payloads.get_platform(payload_name)
                        architecture = self.payloads.get_architecture(
                            payload_name)
                        name = self.payloads.get_name(payload_name)

                        self.badges.output_process("Using default payload " +
                                                   payload_name + "...")

                        if self.payloads.check_exist(payload_name):
                            if self.payloads.add_payload(
                                    full_name, platform, architecture, name):
                                self.add_to_global(module_object)
                            return
                        self.badges.output_error("Invalid default payload!")
                        return
                    self.add_to_global(module_object)
                else:
                    self.badges.output_error(
                        "Failed to select module from database!")
        else:
            self.badges.output_error(
                "Module depends this dependencies which is not installed:")
            for dependence in not_installed:
                self.badges.output_empty("    * " + dependence)

    def add_to_global(self, module_object):
        if self.check_current_module():
            self.local_storage.add_array("current_module", '')
            self.local_storage.set(
                "current_module_number",
                self.local_storage.get("current_module_number") + 1)
            self.local_storage.set_array(
                "current_module",
                self.local_storage.get("current_module_number"), module_object)
        else:
            self.local_storage.set("current_module", [])
            self.local_storage.set("current_module_number", 0)
            self.local_storage.add_array("current_module", '')
            self.local_storage.set_array(
                "current_module",
                self.local_storage.get("current_module_number"), module_object)
예제 #7
0
class Jobs:
    def __init__(self):
        self.exceptions = Exceptions()
        self.tables = Tables()
        self.badges = Badges()
        self.local_storage = LocalStorage()
        self.modules = Modules()

        self.job_process = None

    def stop_dead(self):
        jobs = self.local_storage.get("jobs")
        if jobs:
            for job_id in list(jobs):
                if not jobs[job_id]['job_process'].is_alive():
                    self.delete_job(job_id)

    def check_jobs(self):
        if not self.local_storage.get("jobs"):
            return True
        return False

    def check_module_job(self, module_name):
        jobs = self.local_storage.get("jobs")
        if jobs:
            for job_id in jobs.keys():
                if jobs[job_id]['module_name'] == module_name:
                    return True
        return False

    def exit_jobs(self):
        if self.check_jobs():
            return True
        self.badges.output_warning("You have some running jobs.")
        if self.badges.input_question("Exit anyway? [y/N] ").lower() in [
                'yes', 'y'
        ]:
            self.badges.output_process("Stopping all jobs...")
            self.stop_all_jobs()
            return True
        return False

    def stop_all_jobs(self):
        if not self.check_jobs():
            for job_id in list(self.local_storage.get("jobs").keys()):
                self.delete_job(job_id)

    def stop_job(self, job):
        if job.is_alive():
            exc = ctypes.py_object(SystemExit)
            res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
                ctypes.c_long(job.ident), exc)
            if res == 0:
                raise self.exceptions.GlobalException
            if res > 1:
                ctypes.pythonapi.PyThreadState_SetAsyncExc(job.ident, None)
                raise self.exceptions.GlobalException

    def start_job(self, job_function, job_arguments):
        self.job_process = threading.Thread(target=job_function,
                                            args=job_arguments)
        self.job_process.setDaemon(True)
        self.job_process.start()

    def delete_job(self, job_id):
        if not self.check_jobs():
            job_id = int(job_id)
            if job_id in list(self.local_storage.get("jobs").keys()):
                try:
                    self.stop_job(
                        self.local_storage.get("jobs")[job_id]['job_process'])
                    self.local_storage.delete_element("jobs", job_id)
                except Exception:
                    self.badges.output_error("Failed to stop job!")
            else:
                self.badges.output_error("Invalid job id!")
        else:
            self.badges.output_error("Invalid job id!")

    def create_job(self, job_name, module_name, job_function,
                   job_arguments=()):
        self.start_job(job_function, job_arguments)
        if not self.local_storage.get("jobs"):
            self.local_storage.set("jobs", dict())
        job_id = len(self.local_storage.get("jobs"))
        job_data = {
            job_id: {
                'job_name': job_name,
                'module_name': module_name,
                'job_process': self.job_process
            }
        }
        self.local_storage.update("jobs", job_data)
        return job_id
예제 #8
0
class Importer:
    def __init__(self):
        self.db = DB()
        self.badges = Badges()
        self.local_storage = LocalStorage()
        self.config = Config()
        self.exceptions = Exceptions()

    def get_module(self, mu, name, folderpath):
        folderpath_list = folderpath.split(".")
        for i in dir(mu):
            if i == name:
                return getattr(mu, name)
            if i in folderpath_list:
                i = getattr(mu, i)
                return self.get_module(i, name, folderpath)
        return None

    @staticmethod
    def import_check(module_name):
        try:
            __import__(module_name)
        except ModuleNotFoundError:
            return False
        except Exception:
            return True
        return True

    def import_command(self, command_path):
        try:
            command_directory = command_path
            command_file = os.path.split(command_directory)[1]
            command_directory = command_directory.replace('/', '.')
            command_object = __import__(command_directory)
            command_object = self.get_module(command_object, command_file,
                                             command_directory)
            command_object = command_object.HatSploitCommand()
        except Exception as e:
            self.badges.output_information('Reason: ' + str(e))
            raise self.exceptions.GlobalException
        return command_object

    def import_payload(self, payload_path):
        try:
            payload_directory = payload_path
            payload_file = os.path.split(payload_directory)[1]
            payload_directory = payload_directory.replace('/', '.')
            payload_object = __import__(payload_directory)
            payload_object = self.get_module(payload_object, payload_file,
                                             payload_directory)
            payload_object = payload_object.HatSploitPayload()
        except Exception as e:
            self.badges.output_information('Reason: ' + str(e))
            raise self.exceptions.GlobalException
        return payload_object

    def import_module(self, module_path):
        try:
            module_directory = module_path
            module_file = os.path.split(module_directory)[1]
            module_directory = module_directory.replace('/', '.')
            module_object = __import__(module_directory)
            module_object = self.get_module(module_object, module_file,
                                            module_directory)
            module_object = module_object.HatSploitModule()
        except Exception as e:
            self.badges.output_information('Reason: ' + str(e))
            raise self.exceptions.GlobalException
        return module_object

    def import_plugin(self, plugin_path):
        try:
            plugin_directory = plugin_path
            plugin_file = os.path.split(plugin_directory)[1]
            plugin_directory = plugin_directory.replace('/', '.')
            plugin_object = __import__(plugin_directory)
            plugin_object = self.get_module(plugin_object, plugin_file,
                                            plugin_directory)
            plugin_object = plugin_object.HatSploitPlugin()
        except Exception as e:
            self.badges.output_information('Reason: ' + str(e))
            raise self.exceptions.GlobalException
        return plugin_object

    def import_commands(self):
        commands = dict()
        command_path = self.config.path_config['base_paths']['commands_path']
        try:
            for file in os.listdir(command_path):
                if file.endswith('py'):
                    command_file_path = command_path + file[:-3]
                    command_directory = command_file_path.replace(
                        self.config.path_config['base_paths']['root_path'], '',
                        1)
                    try:
                        command_object = self.import_command(command_directory)
                        command_name = command_object.details['Name']
                        commands[command_name] = command_object
                        self.local_storage.set("commands", commands)
                    except Exception:
                        self.badges.output_error("Failed to load " +
                                                 file[:-3] + " command!")
        except Exception:
            pass

    def import_database(self):
        self.db.connect_payloads_database(
            'hsf_payloads', self.config.path_config['base_paths']['db_path'] +
            self.config.db_config['base_dbs']['payloads_database'])
        self.db.connect_modules_database(
            'hsf_modules', self.config.path_config['base_paths']['db_path'] +
            self.config.db_config['base_dbs']['modules_database'])
        self.db.connect_plugins_database(
            'hsf_plugins', self.config.path_config['base_paths']['db_path'] +
            self.config.db_config['base_dbs']['plugins_database'])

    def import_all(self):
        self.import_commands()
        self.import_database()