Exemplo n.º 1
0
class Update:
    config = Config()
    badges = Badges()

    def check_update(self):
        try:
            remote_config = requests.get(
                'https://raw.githubusercontent.com/EntySec/HatSploit/main/hatsploit/config/core_config.yml',
                stream=True).content
        except Exception:
            remote_config = None

        if remote_config:
            remote_version = self.config.get_config_file(
                remote_config)['details']['version']
            local_version = self.config.core_config['details']['version']

            return version.parse(local_version) < version.parse(remote_version)
        return remote_config

    def update(self):
        if self.check_update():
            self.badges.print_process("Updating HatSploit Framework...")
            shutil.rmtree(os.path.abspath(
                self.config.path_config['root_path']))
            subprocess.call([
                'pip3', 'install', 'git+https://github.com/EntySec/HatSploit',
                '--ignore-installed'
            ],
                            shell=False)
            self.badges.print_success("HatSploit updated successfully!")
            return
        self.badges.print_warning("Your HatSploit is up-to-date.")
Exemplo n.º 2
0
class Tip:
    parser = Parser()
    config = Config()
    badges = Badges()
    colors = Colors()

    colors_script = ColorsScript()

    def print_random_tip(self):
        if os.path.exists(self.config.path_config['tips_path']):
            tips = []
            all_tips = os.listdir(self.config.path_config['tips_path'])
            for tip in all_tips:
                tips.append(tip)
            if tips:
                tip = ""
                while not tip:
                    random_tip = random.randint(0, len(tips) - 1)
                    tip = self.colors_script.parse_colors_script(
                        self.config.path_config['tips_path'] +
                        tips[random_tip])

                self.badges.print_empty(
                    f"%newline%endHatSploit Tip: {tip}%end%newline")
            else:
                self.badges.print_warning("No tips detected.")
        else:
            self.badges.print_warning("No tips detected.")
Exemplo n.º 3
0
class Banner:
    parser = Parser()
    config = Config()
    badges = Badges()
    colors = Colors()

    colors_script = ColorsScript()

    def print_random_banner(self):
        if os.path.exists(self.config.path_config['banners_path']):
            banners = []
            all_banners = os.listdir(self.config.path_config['banners_path'])
            for banner in all_banners:
                banners.append(banner)
            if banners:
                banner = ""
                while not banner:
                    random_banner = random.randint(0, len(banners) - 1)
                    banner = self.colors_script.parse_colors_script(
                        self.config.path_config['banners_path'] + banners[random_banner])

                self.badges.print_empty(f"%newline%end{banner}%end%newline")
            else:
                self.badges.print_warning("No banners detected.")
        else:
            self.badges.print_warning("No banners detected.")
Exemplo n.º 4
0
class HatSploitModule(Module, HTTPClient):
    config = Config()

    details = {
        'Category': "auxiliary",
        'Name': "WEB Directory Scanner",
        'Module': "auxiliary/generic/scanner/directory_scanner",
        'Authors': ['Ivan Nikolsky (enty8080) - module developer'],
        'Description': "Website directory scanner.",
        'Platform': "generic",
        'Rank': "medium"
    }

    options = {
        'HOST': {
            'Description': "Remote host.",
            'Value': None,
            'Type': None,
            'Required': True
        },
        'PORT': {
            'Description': "Remote port.",
            'Value': 80,
            'Type': "port",
            'Required': True
        }
    }

    def run(self):
        remote_host, remote_port = self.parse_options(self.options)

        self.print_process(f"Scanning {remote_host}...")

        with open(f"{self.config.path_config['wordlists_path']}directories.txt"
                  ) as file:
            directories = list(filter(None, file.read().split('\n')))

        for path in directories:
            path = '/' + path.replace("\n", "")

            response = self.http_request(method="HEAD",
                                         host=remote_host,
                                         port=remote_port,
                                         path=path)

            if response is not None:
                if response.status_code == 200:
                    self.print_success(
                        "[%s] ... [%s %s]" %
                        (path, response.status_code, response.reason))
                else:
                    self.print_warning(
                        "[%s] ... [%s %s]" %
                        (path, response.status_code, response.reason))
Exemplo n.º 5
0
class Loader:
    badges = Badges()
    importer = Importer()
    builder = Builder()
    update = Update()

    config = Config()
    build = True

    def load_update_process(self):
        if self.update.check_update():
            self.badges.print_warning("Your HatSploit Framework is out-dated.")
            self.badges.print_information("Consider running %greenhsf --update%end.")
            time.sleep(1)

    def load_components(self):
        if not self.builder.check_base_built() and self.build:
            self.builder.build_base()
        self.importer.import_all(self.build)

    def load_everything(self):
        self.load_components()

    def load_all(self):
        self.load_update_process()

        if not self.builder.check_base_built():
            build = self.badges.input_question("Do you want to build and connect base databases? [y/n] ")
            if build[0].lower() in ['y', 'yes']:
                self.build = True
            else:
                self.build = False

        loading_process = threading.Thread(target=self.load_everything)
        loading_process.start()
        base_line = "Loading the HatSploit Framework..."
        cycle = 0
        while loading_process.is_alive():
            for char in "/-\|":
                status = base_line + char
                cycle += 1
                if status[cycle % len(status)] in list(string.ascii_lowercase):
                    status = status[:cycle % len(status)] + status[cycle % len(status)].upper() + status[cycle % len(
                        status) + 1:]
                elif status[cycle % len(status)] in list(string.ascii_uppercase):
                    status = status[:cycle % len(status)] + status[cycle % len(status)].lower() + status[cycle % len(
                        status) + 1:]
                self.badges.print_process(status, '', '\r')
                time.sleep(.1)
        loading_process.join()
Exemplo n.º 6
0
class Log:
    config = Config()
    badges = Badges()

    storage_path = config.path_config['storage_path']
    global_storage = GlobalStorage(storage_path)

    def enable_log(self, filename):
        if os.access(filename, os.R_OK):
            self.global_storage.set("log", filename)
            self.global_storage.set_all()
            self.badges.print_information("HatSploit log: on")
    
    def disable_log(self):
      self.global_storage.set("log", None)
      self.global_storage.set_all()
      self.badges.print_information("HatSploit log: off")
Exemplo n.º 7
0
    def __init__(self, username, password, host='127.0.0.1', port=8008):
        self.string_tools = StringTools()

        self.fmt = FMT()
        self.execute = Execute()

        self.jobs = Jobs()
        self.options = Options()
        self.modules = Modules()
        self.payloads = Payloads()
        self.sessions = Sessions()
        self.config = Config()

        self.host = host
        self.port = int(port)

        self.username = username
        self.password = password

        self.token = self.string_tools.random_string(32)
Exemplo n.º 8
0
class History:
    config = Config()
    badges = Badges()
    local_storage = LocalStorage()

    history = config.path_config['history_path']
    storage_path = config.path_config['storage_path']

    global_storage = GlobalStorage(storage_path)

    def enable_history(self):
        self.global_storage.set("history", True)
        self.global_storage.set_all()
        self.badges.print_information("HatSploit history: on")

    def disable_history(self):
        self.global_storage.set("history", False)
        self.global_storage.set_all()
        readline.clear_history()
        with open(self.history, 'w') as history:
            history.write("")
        self.badges.print_information("HatSploit history: off")

    def clear_history(self):
        readline.clear_history()
        with open(self.history, 'w') as history:
            history.write("")

    def list_history(self):
        using_history = self.local_storage.get("history")
        if using_history:
            if readline.get_current_history_length() > -1:
                self.badges.print_information("HatSploit history:")

                for index in range(1, readline.get_current_history_length() + 1):
                    self.badges.print_empty("    * " + readline.get_history_item(index))
            else:
                self.badges.print_warning("HatSploit history empty.")
        else:
            self.badges.print_warning("No HatSploit history detected.")
Exemplo n.º 9
0
class Loot(StringTools, FSTools):
    badges = Badges()

    loot = Config().path_config['loot_path']
    data = Config().path_config['data_path']

    def create_loot(self):
        if not os.path.isdir(self.loot):
            os.mkdir(self.loot)

    def specific_loot(self, filename):
        return self.loot + filename

    def random_loot(self, extension=None):
        filename = self.random_string(16)

        if extension:
            filename += '.' + extension

        return self.loot + filename

    def get_file(self, filename):
        if self.exists_file(filename):
            with open(filename, 'rb') as f:
                return f.read()

        return None

    def save_file(self, location, data, extension=None, filename=None):
        exists, is_dir = self.exists(location)

        if exists:
            if is_dir:
                if location.endswith('/'):
                    location += os.path.split(
                        filename)[1] if filename else self.random_string(16)
                else:
                    location += '/' + os.path.split(
                        filename)[1] if filename else self.random_string(16)

            if extension:
                if not location.endswith('.' + extension):
                    location += '.' + extension

            with open(location, 'wb') as f:
                f.write(data)

            self.badges.print_success(f"Saved to {location}!")
            return os.path.abspath(location)

        return None

    def remove_file(self, filename):
        if self.exists_file(filename):
            os.remove(filename)

            self.badges.print_success(f"Removed {filename}!")
            return True

        return False

    def get_loot(self, filename):
        filename = os.path.split(filename)[1]
        return self.get_file(self.loot + filename)

    def save_loot(self, filename, data):
        filename = os.path.split(filename)[1]
        return self.save_file(self.loot + filename, data)

    def remove_loot(self, filename):
        filename = os.path.split(filename)[1]
        return self.remove_file(self.loot + filename)

    def get_data(self, filename):
        if os.path.exists(self.data + filename):
            with open(self.data + filename, 'rb') as f:
                return f.read()
        else:
            self.badges.print_error("Invalid data given!")

    def list_loot(self):
        loots = []

        for loot in os.listdir(self.loot):
            loots.append(
                (loot, self.loot + loot,
                 datetime.datetime.fromtimestamp(
                     os.path.getmtime(self.loot + loot)).astimezone().strftime(
                         "%Y-%m-%d %H:%M:%S %Z")))

        return loots
Exemplo n.º 10
0
class Builder:
    modules = Modules()
    payloads = Payloads()
    badges = Badges()
    config = Config()
    importer = Importer()
    local_storage = LocalStorage()

    def check_base_built(self):
        if (os.path.exists(self.config.path_config['db_path'] +
                           self.config.db_config['base_dbs']['module_database']) and
                os.path.exists(self.config.path_config['db_path'] +
                               self.config.db_config['base_dbs']['payload_database']) and
                os.path.exists(self.config.path_config['db_path'] +
                               self.config.db_config['base_dbs']['plugin_database'])):
            return True
        return False

    def build_base(self):
        if not self.check_base_built():
            if not os.path.exists(self.config.path_config['db_path']):
                os.mkdir(self.config.path_config['db_path'])

            self.build_module_database(self.config.path_config['modules_path'],
                                        (self.config.path_config['db_path'] +
                                         self.config.db_config['base_dbs']['module_database']))
            self.build_payload_database(self.config.path_config['payloads_path'],
                                         (self.config.path_config['db_path'] +
                                          self.config.db_config['base_dbs']['payload_database']))
            self.build_plugin_database(self.config.path_config['plugins_path'],
                                        (self.config.path_config['db_path'] +
                                         self.config.db_config['base_dbs']['plugin_database']))

    def build_payload_database(self, input_path, output_path):
        database_path = output_path
        database = {
            "__database__": {
                "type": "payloads"
            }
        }

        payloads_path = os.path.normpath(input_path)
        for dest, _, files in os.walk(payloads_path):
            for file in files:
                if file.endswith('.py') and file != '__init__.py':
                    payload = dest + '/' + file[:-3]

                    try:
                        payload_object = self.importer.import_payload(payload)
                        payload_name = payload_object.details['Payload']

                        database.update({
                            payload_name: {
                                "Path": payload,
                                "Category": payload_object.details['Category'],
                                "Name": payload_object.details['Name'],
                                "Payload": payload_object.details['Payload'],
                                "Authors": payload_object.details['Authors'],
                                "Description": payload_object.details['Description'],
                                "Architecture": payload_object.details['Architecture'],
                                "Platform": payload_object.details['Platform'],
                                "Rank": payload_object.details['Rank'],
                                "Type": payload_object.details['Type']
                            }
                        })
                    except Exception:
                        self.badges.print_error(f"Failed to add {payload} to payload database!")

        with open(database_path, 'w') as f:
            json.dump(database, f)

    def build_module_database(self, input_path, output_path):
        database_path = output_path
        database = {
            "__database__": {
                "type": "modules"
            }
        }

        modules_path = os.path.normpath(input_path)
        for dest, _, files in os.walk(modules_path):
            for file in files:
                if file.endswith('.py') and file != '__init__.py':
                    module = dest + '/' + file[:-3]

                    try:
                        module_object = self.importer.import_module(module)
                        module_name = module_object.details['Module']

                        database.update({
                            module_name: {
                                "Path": module,
                                "Category": module_object.details['Category'],
                                "Name": module_object.details['Name'],
                                "Module": module_object.details['Module'],
                                "Authors": module_object.details['Authors'],
                                "Description": module_object.details['Description'],
                                "Platform": module_object.details['Platform'],
                                "Rank": module_object.details['Rank']
                            }
                        })
                    except Exception:
                        self.badges.print_error(f"Failed to add {module} to module database!")

        with open(database_path, 'w') as f:
            json.dump(database, f)

    def build_plugin_database(self, input_path, output_path):
        database_path = output_path
        database = {
            "__database__": {
                "type": "plugins"
            }
        }

        plugins_path = os.path.normpath(input_path)
        for dest, _, files in os.walk(plugins_path):
            for file in files:
                if file.endswith('.py') and file != '__init__.py':
                    plugin = dest + '/' + file[:-3]

                    try:
                        plugin_object = self.importer.import_plugin(plugin)
                        plugin_name = plugin_object.details['Plugin']

                        database.update({
                            plugin_name: {
                                "Path": plugin,
                                "Name": plugin_object.details['Name'],
                                "Plugin": plugin_object.details['Plugin'],
                                "Authors": plugin_object.details['Authors'],
                                "Description": plugin_object.details['Description']
                            }
                        })
                    except Exception:
                        self.badges.print_error(f"Failed to add {plugin} to plugin database!")

        with open(database_path, 'w') as f:
            json.dump(database, f)
Exemplo n.º 11
0
class HatSploitCommand(Command):
    config = Config()

    storage_path = config.path_config['storage_path']

    local_storage = LocalStorage()
    global_storage = GlobalStorage(storage_path)

    details = {
        'Category': "developer",
        'Name': "storage",
        'Authors': ['Ivan Nikolsky (enty8080) - command developer'],
        'Description': "Manage storage variables.",
        'Usage': "storage [global|local] <option> [arguments]",
        'MinArgs': 2,
        'Options': {
            '-l': ['', "List all storage variables."],
            '-v': ['<name>', "Show specified storage variable value."],
            '-s': ['<name> <value>', "Set storage variable value."],
            '-d': ['<name>', "Delete storage variable."]
        }
    }

    def run(self, argc, argv):
        type_of_storage = argv[1]

        if type_of_storage == "global":
            choice = argv[2]
            if choice in ['-l', '--list']:
                self.print_information("Global storage variables:")
                for variable in self.global_storage.get_all():
                    if not str.startswith(variable, '__') and not str.endswith(
                            variable, '__'):
                        self.print_empty("    * " + variable)
            elif choice in ['-v', '--value']:
                if argv[3] in self.global_storage.get_all():
                    self.print_information(
                        argv[3] + " = " +
                        str(self.global_storage.get(argv[3])))
            elif choice in ['-s', '--set']:
                self.global_storage.set(argv[3], argv[4])
            elif choice in ['-d', '--delete']:
                if argv[3] in self.global_storage.get_all():
                    self.global_storage.delete(argv[3])
                else:
                    self.print_error("Invalid storage variable name!")
        elif type_of_storage == "local":
            choice = argv[2]
            if choice in ['-l', '--list']:
                self.print_information("Local storage variables:")
                for variable in self.local_storage.get_all():
                    if not str.startswith(variable, '__') and not str.endswith(
                            variable, '__'):
                        self.print_empty("    * " + variable)
            elif choice in ['-v', '--value']:
                if argv[3] in self.local_storage.get_all():
                    self.print_information(
                        argv[3] + " = " + str(self.local_storage.get(argv[3])))
                else:
                    self.print_error("Invalid storage variable name!")
            elif choice in ['-s', '--set']:
                self.local_storage.set(argv[3], argv[4])
            elif choice in ['-d', '--delete']:
                if argv[3] in self.local_storage.get_all():
                    self.local_storage.delete(argv[3])
                else:
                    self.print_error("Invalid storage variable name!")
Exemplo n.º 12
0
class Check:
    config = Config()
    importer = Importer()
    badges = Badges()

    def check_modules(self):
        one_fail = False
        self.badges.print_process("Checking all base modules...")

        modules_path = os.path.normpath(
            self.config.path_config['modules_path'])
        for dest, _, files in os.walk(modules_path):
            for file in files:
                if file.endswith('.py') and file != '__init__.py':
                    module = dest + '/' + file[:-3]

                    try:
                        module_object = self.importer.import_module(module)
                        keys = [
                            'Category', 'Name', 'Module', 'Authors',
                            'Description', 'Platform', 'Rank'
                        ]
                        assert (all(key in module_object.details
                                    for key in keys))
                        self.badges.print_success(f"{module}: OK")
                    except Exception:
                        self.badges.print_error(f"{module}: FAIL")
                        one_fail = True
        return not one_fail

    def check_payloads(self):
        one_fail = False
        self.badges.print_process("Checking all base payloads...")

        payloads_path = os.path.normpath(
            self.config.path_config['payloads_path'])
        for dest, _, files in os.walk(payloads_path):
            for file in files:
                if file.endswith('.py') and file != '__init__.py':
                    payload = dest + '/' + file[:-3]

                    try:
                        payload_object = self.importer.import_payload(payload)
                        keys = [
                            'Category', 'Name', 'Payload', 'Authors',
                            'Description', 'Architecture', 'Platform', 'Rank',
                            'Type'
                        ]
                        assert (all(key in payload_object.details
                                    for key in keys))
                        self.badges.print_success(f"{payload}: OK")
                    except Exception:
                        self.badges.print_error(f"{payload}: FAIL")
                        one_fail = True
        return not one_fail

    def check_plugins(self):
        one_fail = False
        self.badges.print_process("Checking all base plugins...")

        plugins_path = os.path.normpath(
            self.config.path_config['plugins_path'])
        for dest, _, files in os.walk(plugins_path):
            for file in files:
                if file.endswith('.py') and file != '__init__.py':
                    plugin = dest + '/' + file[:-3]

                    try:
                        plugin_object = self.importer.import_plugin(plugin)
                        keys = ['Name', 'Authors', 'Description']
                        assert (all(key in plugin_object.details
                                    for key in keys))
                        self.badges.print_success(f"{plugin}: OK")
                    except Exception:
                        self.badges.print_error(f"{plugin}: FAIL")
                        one_fail = True
        return not one_fail

    def check_all(self):
        fails = []

        fails.append(self.check_modules())
        fails.append(self.check_payloads())
        fails.append(self.check_plugins())

        for fail in fails:
            if not fail:
                self.badges.print_error("Not all checks passed!")
                return False
        self.badges.print_success("All checks passed!")
        return True
Exemplo n.º 13
0
class Sessions:
    badges = Badges()
    config = Config()

    storage_path = config.path_config['storage_path']

    global_storage = GlobalStorage(storage_path)
    local_storage = LocalStorage()

    def get_all_sessions(self):
        sessions = self.local_storage.get("sessions")
        return sessions

    def close_dead(self):
        sessions = self.local_storage.get("sessions")
        if sessions:
            for session in list(sessions):
                if not sessions[session]['object'].heartbeat():
                    self.badges.print_warning(
                        f"Session {str(session)} is dead (no heartbeat).")
                    self.close_session(session)

    def close_sessions(self):
        if not self.local_storage.get("sessions"):
            return True
        self.badges.print_warning("You have some opened sessions.")
        if self.badges.input_question("Exit anyway? [y/N] ")[0].lower() in [
                'yes', 'y'
        ]:
            self.badges.print_process("Closing all sessions...")
            self.close_all_sessions()
            return True
        return False

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

        session_id = 0
        while (session_id in self.local_storage.get("sessions")
               or session_id < len(self.local_storage.get("sessions"))):
            session_id += 1

        sessions = {
            session_id: {
                'platform': session_platform,
                'architecture': session_architecture,
                'type': session_type,
                'host': session_host,
                'port': session_port,
                'object': session_object
            }
        }

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

    def check_exist(self,
                    session_id,
                    session_platform=None,
                    session_architecture=None,
                    session_type=None):
        sessions = self.local_storage.get("sessions")
        if sessions:
            if int(session_id) in sessions:
                valid = True

                if session_platform:
                    if sessions[int(
                            session_id)]['platform'] != session_platform:
                        valid = False

                if session_type:
                    if sessions[int(session_id)]['type'] != session_type:
                        valid = False

                if session_architecture:
                    if sessions[int(session_id
                                    )]['architecture'] != session_architecture:
                        valid = False

                return valid
        return False

    def enable_auto_interaction(self):
        self.global_storage.set("auto_interaction", True)
        self.global_storage.set_all()
        self.badges.print_information("Auto interaction: on")

    def disable_auto_interaction(self):
        self.global_storage.set("auto_interaction", False)
        self.global_storage.set_all()
        self.badges.print_information("Auto interaction: off")

    def interact_with_session(self, session_id):
        sessions = self.local_storage.get("sessions")
        if self.check_exist(session_id):
            self.badges.print_process(
                f"Interacting with session {str(session_id)}...%newline")
            sessions[int(session_id)]['object'].interact()
        else:
            self.badges.print_error("Invalid session given!")

    def session_download(self, session_id, remote_file, local_path):
        sessions = self.local_storage.get("sessions")
        if self.check_exist(session_id):
            return sessions[int(session_id)]['object'].download(
                remote_file, local_path)
        self.badges.print_error("Invalid session given!")
        return None

    def session_upload(self, session_id, local_file, remote_path):
        sessions = self.local_storage.get("sessions")
        if self.check_exist(session_id):
            return sessions[int(session_id)]['object'].upload(
                local_file, remote_path)
        self.badges.print_error("Invalid session given!")
        return None

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

                self.local_storage.update("sessions", sessions)
            except Exception:
                self.badges.print_error("Failed to close session!")
        else:
            self.badges.print_error("Invalid session given!")

    def close_all_sessions(self):
        sessions = self.local_storage.get("sessions")
        if sessions:
            for session in list(sessions):
                try:
                    sessions[session]['object'].close()
                    del sessions[session]

                    self.local_storage.update("sessions", sessions)
                except Exception:
                    self.badges.print_error("Failed to close session!")

    def get_session(self,
                    session_id,
                    session_platform=None,
                    session_architecture=None,
                    session_type=None):
        sessions = self.local_storage.get("sessions")
        if self.check_exist(session_id, session_platform, session_architecture,
                            session_type):
            return sessions[int(session_id)]['object']
        self.badges.print_error("Invalid session given!")
        return None
Exemplo n.º 14
0
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#

import sys

sys.stdout.write("\033]0;HatSploit Framework\007")

import os
import yaml
import argparse

from hatsploit.lib.config import Config

config = Config()
config.configure()

from hatsploit.lib.jobs import Jobs

from hatsploit.core.base.console import Console
from hatsploit.core.cli.badges import Badges
from hatsploit.core.utils.check import Check
from hatsploit.core.utils.api import API
from hatsploit.core.utils.update import Update


class HatSploit:
    jobs = Jobs()
    console = Console()
    badges = Badges()
Exemplo n.º 15
0
class Console:
    exceptions = Exceptions()
    execute = Execute()
    loader = Loader()

    fmt = FMT()
    badges = Badges()

    completer = Completer()
    banner = Banner()
    tip = Tip()

    loot = Loot()

    config = Config()
    jobs = Jobs()
    options = Options()
    sessions = Sessions()
    modules = Modules()
    payloads = Payloads()
    local_storage = LocalStorage()

    history = config.path_config['history_path']
    prompt = config.core_config['details']['prompt']

    handler_options = {
        'Module': {},
        'Payload': {}
    }

    completion = None

    def check_install(self):
        if os.path.exists(self.config.path_config['root_path']):
            workspace = self.config.path_config['user_path']
            loot = self.config.path_config['loot_path']

            if not os.path.isdir(workspace):
                self.badges.print_process(f"Creating workspace at {workspace}...")
                os.mkdir(workspace)

            if not os.path.isdir(loot):
                self.loot.create_loot()

            return True
        self.badges.print_error("HatSploit is not installed!")
        self.badges.print_information("Consider running installation.")
        return False

    def start_hsf(self):
        try:
            self.loader.load_all()
        except Exception:
            sys.exit(1)

    def update_events(self):
        current_module = self.modules.get_current_module_object()
        current_payload = self.payloads.get_current_payload()

        self.jobs.stop_dead()
        self.sessions.close_dead()

        self.options.add_handler_options(current_module, current_payload)

    def launch_menu(self):
        while True:
            try:
                if not self.modules.check_current_module():
                    prompt = f'({self.prompt})> '
                else:
                    current_module = self.modules.get_current_module_object()

                    category = current_module.details['Category']
                    name = current_module.details['Name']

                    prompt = f'({self.prompt}: {category}: %red{name}%end)> '
                commands = self.badges.input_empty(prompt)

                self.update_events()
                self.execute.execute_command(commands)
                self.update_events()

                if self.local_storage.get("history"):
                    readline.write_history_file(self.history)

            except (KeyboardInterrupt, EOFError, self.exceptions.GlobalException):
                pass
            except Exception as e:
                self.badges.print_error(f"An error occurred: {str(e)}!")

    def enable_history_file(self):
        if not os.path.exists(self.history):
            open(self.history, 'w').close()
        readline.read_history_file(self.history)

    def launch_history(self):
        readline.set_auto_history(False)

        using_history = self.local_storage.get("history")
        if using_history:
            readline.set_auto_history(True)
            self.enable_history_file()

        readline.set_completer(self.completer.completer)
        readline.set_completer_delims(" \t\n;")

        readline.parse_and_bind("tab: complete")

    def launch_shell(self):
        version = self.config.core_config['details']['version']
        codename = self.config.core_config['details']['codename']

        if self.config.core_config['console']['clear']:
            self.badges.print_empty("%clear", end='')

        if self.config.core_config['console']['banner']:
            self.banner.print_random_banner()

        if self.config.core_config['console']['header']:
            plugins = self.local_storage.get("plugins")
            modules = self.local_storage.get("modules")
            payloads = self.local_storage.get("payloads")

            plugins_total = 0
            modules_total = 0
            payloads_total = 0

            if payloads:
                for database in payloads:
                    payloads_total += len(payloads[database])
            if plugins:
                for database in plugins:
                    plugins_total += len(plugins[database])
            if modules:
                for database in modules:
                    modules_total += len(modules[database])

            header = ""
            header += "%end"
            if codename:
                header += f"    --=( %yellowHatSploit Framework {version} {codename}%end\n"
            else:
                header += f"    --=( %yellowHatSploit Framework {version}%end\n"
            header += "--==--=( Developed by EntySec (%linehttps://entysec.netlify.app/%end)\n"
            header += f"    --=( {modules_total} modules | {payloads_total} payloads | {plugins_total} plugins"
            header += "%end"

            self.badges.print_empty(header)

        if self.config.core_config['console']['tip']:
            self.tip.print_random_tip()

    def shell(self):
        self.start_hsf()
        self.launch_history()
        self.launch_shell()
        self.launch_menu()

    def script(self, input_files, do_shell=False):
        self.start_hsf()
        self.launch_shell()

        for input_file in input_files:
            if os.path.exists(input_file):
                file = open(input_file, 'r')
                file_text = file.read().split('\n')
                file.close()

                for line in file_text:
                    commands = self.fmt.format_commands(line)

                    self.add_handler_options()
                    self.jobs.stop_dead()

                    self.execute.execute_command(commands)

        if do_shell:
            self.launch_history()
            self.launch_menu()
Exemplo n.º 16
0
class DB:
    badges = Badges()
    config = Config()
    local_storage = LocalStorage()

    def disconnect_payload_database(self, name):
        if self.local_storage.get("connected_payload_databases"):
            if name in self.local_storage.get("connected_payload_databases"):
                self.local_storage.delete_element(
                    "connected_payload_databases", name)
                self.local_storage.delete_element("payloads", name)
                return
        self.badges.print_error("No such payload database connected!")

    def disconnect_module_database(self, name):
        if self.local_storage.get("connected_module_databases"):
            if name in self.local_storage.get("connected_module_databases"):
                self.local_storage.delete_element("connected_module_databases",
                                                  name)
                self.local_storage.delete_element("modules", name)
                return
        self.badges.print_error("No such module database connected!")

    def disconnect_plugin_database(self, name):
        if self.local_storage.get("connected_plugin_databases"):
            if name in self.local_storage.get("connected_plugin_databases"):
                self.local_storage.delete_element("connected_plugin_databases",
                                                  name)
                self.local_storage.delete_element("plugins", name)
                return
        self.badges.print_error("No such plugin database connected!")

    def connect_payload_database(self, name, path):
        if self.local_storage.get("connected_payload_databases"):
            if name in self.local_storage.get("connected_payload_databases"):
                self.badges.print_error("Payload database already connected!")
                return
        if not os.path.exists(path) or not str.endswith(path, "json"):
            self.badges.print_error("Not a payload database!")
            return

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

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

        payloads = {name: database}

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

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

    def connect_module_database(self, name, path):
        if self.local_storage.get("connected_module_databases"):
            if name in self.local_storage.get("connected_module_databases"):
                self.badges.print_error("Module database already connected!")
                return
        if not os.path.exists(path) or not str.endswith(path, "json"):
            self.badges.print_error("Not a module database!")
            return

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

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

        modules = {name: database}

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

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

    def connect_plugin_database(self, name, path):
        if self.local_storage.get("connected_plugin_databases"):
            if name in self.local_storage.get("connected_plugin_databases"):
                self.badges.print_error("Plugin database already connected!")
                return
        if not os.path.exists(path) or not str.endswith(path, "json"):
            self.badges.print_error("Not a database!")
            return

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

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

        plugins = {name: database}

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

        if self.local_storage.get("plugins"):
            self.local_storage.update("plugins", plugins)
        else:
            self.local_storage.set("plugins", plugins)
Exemplo n.º 17
0
class Importer:
    db = DB()
    badges = Badges()
    local_storage = LocalStorage()
    config = Config()
    exceptions = Exceptions()

    @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:
            if not command_path.endswith('.py'):
                command_path = command_path + '.py'
            spec = importlib.util.spec_from_file_location(
                command_path, command_path)
            command = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(command)
            command = command.HatSploitCommand()
        except Exception as e:
            self.badges.print_information('Reason: ' + str(e))
            raise self.exceptions.GlobalException
        return command

    def import_payload(self, payload_path):
        try:
            if not payload_path.endswith('.py'):
                payload_path = payload_path + '.py'
            spec = importlib.util.spec_from_file_location(
                payload_path, payload_path)
            payload = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(payload)
            payload = payload.HatSploitPayload()
        except Exception as e:
            self.badges.print_information('Reason: ' + str(e))
            raise self.exceptions.GlobalException
        return payload

    def import_module(self, module_path):
        try:
            if not module_path.endswith('.py'):
                module_path = module_path + '.py'
            spec = importlib.util.spec_from_file_location(
                module_path, module_path)
            module = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(module)
            module = module.HatSploitModule()
        except Exception as e:
            self.badges.print_information('Reason: ' + str(e))
            raise self.exceptions.GlobalException
        return module

    def import_plugin(self, plugin_path):
        try:
            if not plugin_path.endswith('.py'):
                plugin_path = plugin_path + '.py'
            spec = importlib.util.spec_from_file_location(
                plugin_path, plugin_path)
            plugin = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(plugin)
            plugin = plugin.HatSploitPlugin()
        except Exception as e:
            self.badges.print_information('Reason: ' + str(e))
            raise self.exceptions.GlobalException
        return plugin

    def import_main_commands(self):
        commands = self.import_commands(
            self.config.path_config['commands_path'])
        self.local_storage.set("commands", commands)

    def import_commands(self, path):
        if not path.endswith('/'):
            path += '/'

        commands = {}
        command_path = os.path.split(path)[0]
        try:
            for file in os.listdir(command_path):
                if file.endswith('py'):
                    try:
                        command_object = self.import_command(command_path +
                                                             '/' + file[:-3])
                        command_name = command_object.details['Name']
                        commands[command_name] = command_object
                    except Exception:
                        self.badges.print_error(
                            f"Failed to load {file[:-3]} command!")
        except Exception:
            pass
        return commands

    def import_database(self):
        self.db.connect_module_database(
            self.config.db_config['base_dbs']['module_database_name'],
            self.config.path_config['db_path'] +
            self.config.db_config['base_dbs']['module_database'])
        self.db.connect_payload_database(
            self.config.db_config['base_dbs']['payload_database_name'],
            self.config.path_config['db_path'] +
            self.config.db_config['base_dbs']['payload_database'])
        self.db.connect_plugin_database(
            self.config.db_config['base_dbs']['plugin_database_name'],
            self.config.path_config['db_path'] +
            self.config.db_config['base_dbs']['plugin_database'])

    def import_all(self, import_database):
        self.import_main_commands()
        if import_database:
            self.import_database()