Beispiel #1
0
class HatSploitCommand(Command):
    modules = Modules()
    jobs = Jobs()

    details = {
        'Category': "modules",
        'Name': "run",
        'Authors': ['Ivan Nikolsky (enty8080) - command developer'],
        'Description': "Run current module.",
        'Usage': "run [option]",
        'MinArgs': 0,
        'Options': {
            '-j': ['', "Run current module as a background job."]
        }
    }

    def run(self, argc, argv):
        current_module = self.modules.get_current_module_object()

        if argc > 1:
            if argv[1] == '-j' and current_module:
                job_id = self.jobs.count_jobs()

                self.print_process("Running module as a background job...")
                self.print_information(
                    f"Module started as a background job {str(job_id)}.")

                self.jobs.create_job(current_module.details['Name'],
                                     current_module.details['Module'],
                                     self.modules.run_current_module)
                return

        self.modules.run_current_module()
Beispiel #2
0
class HatSploitCommand(Command):
    modules = Modules()
    show = Show()

    details = {
        'Category': "modules",
        'Name': "info",
        'Authors': ['Ivan Nikolsky (enty8080) - command developer'],
        'Description': "Show module information.",
        'Usage': "info [<module>]",
        'MinArgs': 0
    }

    complete = modules.modules_completer

    def get_module_information(self, module):
        if self.modules.check_exist(module):
            module = self.modules.get_module_object(module)
            self.show.show_module_information(module)
        else:
            self.print_error("Invalid module!")

    def run(self, argc, argv):
        if self.modules.check_current_module():
            if argc > 1:
                self.get_module_information(argv[1])
            else:
                self.show.show_module_information(
                    self.modules.get_current_module_object().details)
        else:
            if argc > 1:
                self.get_module_information(argv[1])
            else:
                self.print_usage(self.details['Usage'])
Beispiel #3
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)
Beispiel #4
0
class HatSploitCommand(Command):
    modules = Modules()

    details = {
        'Category': "modules",
        'Name': "use",
        'Authors': ['Ivan Nikolsky (enty8080) - command developer'],
        'Description': "Use specified module.",
        'Usage': "use <module|number>",
        'MinArgs': 1
    }

    complete = modules.modules_completer

    def run(self, argc, argv):
        self.modules.use_module(argv[1])
Beispiel #5
0
class HatSploitCommand(Command):
    modules = Modules()

    details = {
        'Category': "modules",
        'Name': "back",
        'Authors': [
            'Ivan Nikolsky (enty8080) - command developer'
        ],
        'Description': "Return to the previous module.",
        'Usage': "back",
        'MinArgs': 0
    }

    def run(self, argc, argv):
        self.modules.go_back()
Beispiel #6
0
class HatSploitCommand(Command):
    modules = Modules()
    execute = Execute()

    details = {
        'Category': "modules",
        'Name': "edit",
        'Authors': ['Ivan Nikolsky (enty8080) - command developer'],
        'Description': "Open module in editor.",
        'Usage': "edit <module>",
        'MinArgs': 1
    }

    complete = modules.modules_completer

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

        try:
            if not os.environ['EDITOR']:
                self.print_warning("Shell variable EDITOR not set.")
                editor = "vi"
            else:
                editor = os.environ['EDITOR']
        except KeyError:
            self.print_warning("Shell variable EDITOR not set.")
            editor = "vi"

        if self.modules.check_exist(module):
            if not self.modules.check_imported(module):
                database = self.modules.get_database(module)
                module_path = self.modules.get_modules(
                )[database][module]['Path']

                edit_mode = editor + ' ' + module_path + '.py'
                self.execute.execute_system(self.format_commands(edit_mode))
            else:
                self.print_error("Can not edit already used module!")
        else:
            self.print_error("Invalid module!")
Beispiel #7
0
class HatSploitCommand(Command):
    modules = Modules()
    show = Show()

    details = {
        'Category': "modules",
        'Name': "modules",
        'Authors': ['Ivan Nikolsky (enty8080) - command developer'],
        'Description': "Show available modules.",
        'Usage': "modules [category]",
        'MinArgs': 0
    }

    def collect_categories(self):
        modules = self.modules.get_modules()
        categories = []

        if modules:
            for database in sorted(modules):
                for module in sorted(modules[database]):
                    category = modules[database][module]['Category']

                    if category not in categories:
                        categories.append(category)

        return categories

    def run(self, argc, argv):
        categories = self.collect_categories()

        if argc > 1:
            if argv[1] in categories:
                self.show.show_modules(argv[1])
            else:
                self.print_error("Invalid module category!")
                self.print_information(
                    f"Available categories: {str(categories)}")
        else:
            self.show.show_modules()
Beispiel #8
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)
Beispiel #9
0
class Commands:
    show = Show()

    importer = Importer()
    badges = Badges()
    execute = Execute()

    modules = Modules()
    local_storage = LocalStorage()

    def load_commands(self, path):
        return self.importer.import_commands(path)

    def execute_command(self, commands):
        self.execute.execute_command(commands)

    def execute_system_command(self, commands):
        self.execute.execute_system(commands)

    def execute_custom_command(self, commands, handler, error=True):
        if commands:
            if not self.execute.execute_builtin_method(commands):
                if not self.execute.execute_custom_command(commands, handler):
                    if error:
                        self.badges.print_error(
                            f"Unrecognized command: {commands[0]}!")
                    return False
        return True

    def show_commands(self, handler):
        self.show.show_custom_commands(handler)

    def commands_completer(self, text):
        return [
            command for command in self.get_all_commands()
            if command.startswith(text)
        ]

    def get_commands(self):
        return self.local_storage.get("commands")

    def get_modules_commands(self):
        module = self.modules.get_current_module_object()

        if module:
            return module.commands if hasattr(module, "commands") else {}
        return {}

    def get_plugins_commands(self):
        plugins = self.local_storage.get("loaded_plugins")
        commands = {}

        if plugins:
            for plugin in plugins:
                if hasattr(plugins[plugin], "commands"):
                    for label in plugins[plugin].commands:
                        commands.update(plugins[plugin].commands[label])

        return commands

    def get_all_commands(self):
        commands = {}
        module = self.modules.get_current_module_object()

        if module:
            if hasattr(module, "commands"):
                commands.update(module.commands)

        plugins = self.local_storage.get("loaded_plugins")

        if plugins:
            for plugin in plugins:
                if hasattr(plugins[plugin], "commands"):
                    for label in plugins[plugin].commands:
                        commands.update(plugins[plugin].commands[label])

        commands.update(self.local_storage.get("commands"))
        return commands
Beispiel #10
0
class Execute:
    jobs = Jobs()
    fmt = FMT()
    badges = Badges()
    tables = Tables()
    local_storage = LocalStorage()
    modules = Modules()
    show = Show()

    def execute_command(self, commands):
        if commands:
            if not self.execute_builtin_method(commands):
                if not self.execute_core_command(commands):
                    if not self.execute_module_command(commands):
                        if not self.execute_plugin_command(commands):
                            self.badges.print_error(
                                f"Unrecognized command: {commands[0]}!")

    def execute_builtin_method(self, commands):
        if commands[0][0] == '#':
            return True
        if commands[0][0] == '?':
            self.show.show_all_commands()
            return True
        if commands[0][0] == '&':
            commands[0] = commands[0][1:]

            self.jobs.create_job(commands[0], None, self.execute_command,
                                 [commands], True)

            return True
        if commands[0][0] == '!':
            if len(commands[0]) > 1:
                commands[0] = commands[0].replace('!', '', 1)
                self.execute_system(commands)
            else:
                self.badges.print_usage("!<command>")
            return True
        return False

    def execute_system(self, commands):
        self.badges.print_process(f"Executing system command: {commands[0]}\n")
        try:
            subprocess.call(commands)
        except Exception:
            self.badges.print_error(
                f"Unrecognized system command: {commands[0]}!")

    def execute_custom_command(self, commands, handler):
        if handler:
            if commands[0] in handler:
                command = handler[commands[0]]
                if not self.check_arguments(commands, command.details):
                    self.parse_usage(command.details)
                else:
                    command.run(len(commands), commands)
                return True
        return False

    def check_arguments(self, commands, details):
        if (len(commands) - 1) < details['MinArgs']:
            return False
        if 'Options' in details:
            if len(commands) > 1:
                if commands[1] in details['Options']:
                    if (len(commands) - 2) < len(
                            details['Options'][commands[1]][0].split()):
                        return False
                else:
                    return False

        if len(commands) > 1:
            if commands[1] == '?':
                return False

        return True

    def parse_usage(self, details):
        self.badges.print_usage(details['Usage'])

        if 'Options' in details:
            headers = ('Option', 'Arguments', 'Description')
            data = []

            for option in details['Options']:
                info = details['Options'][option]
                data.append((option, info[0], info[1]))

            self.tables.print_table('Options', headers, *data)

    def execute_core_command(self, commands):
        return self.execute_custom_command(commands,
                                           self.local_storage.get("commands"))

    def execute_module_command(self, commands):
        if self.modules.check_current_module():
            if hasattr(self.modules.get_current_module_object(), "commands"):
                if commands[0] in self.modules.get_current_module_object(
                ).commands:
                    command_object = self.modules.get_current_module_object()
                    command = self.modules.get_current_module_object(
                    ).commands[commands[0]]
                    self.parse_and_execute_command(commands, command,
                                                   command_object)
                    return True
        return False

    def execute_plugin_command(self, commands):
        if self.local_storage.get("loaded_plugins"):
            for plugin in self.local_storage.get("loaded_plugins"):
                if hasattr(
                        self.local_storage.get("loaded_plugins")[plugin],
                        "commands"):
                    for label in self.local_storage.get(
                            "loaded_plugins")[plugin].commands:
                        if commands[0] in self.local_storage.get(
                                "loaded_plugins")[plugin].commands[label]:
                            command_object = self.local_storage.get(
                                "loaded_plugins")[plugin]
                            command = command_object.commands[label][
                                commands[0]]
                            self.parse_and_execute_command(
                                commands, command, command_object)
                            return True
        return False

    def parse_and_execute_command(self, commands, command, command_object):
        if hasattr(command_object, commands[0]):
            if not self.check_arguments(commands, command):
                self.parse_usage(command)
            else:
                getattr(command_object, commands[0])(len(commands), commands)
        else:
            self.badges.print_error("Failed to execute command!")
Beispiel #11
0
class Handler:
    blinder = Blinder()
    post = Post()
    post_tools = PostTools()
    server_handle = Handle()

    sessions = Sessions()
    modules = Modules()
    jobs = Jobs()
    types = TypeTools()
    badges = Badges()
    local_storage = LocalStorage()

    def do_job(self, payload_type, target, args):
        if payload_type == 'one_side':
            target(*args)
        else:
            self.jobs.create_job(
                None,
                None,
                target,
                args,
                True
            )

    def ensure_linemax(self, payload, linemax):
        min_size = 10000
        max_size = 100000

        if len(payload) >= max_size and linemax not in range(min_size, max_size):
            self.badges.print_process(f"Ensuring payload size ({str(len(payload))} bytes)...")
            linemax = max_size

        return linemax

    def send(self, sender, payload, args={}):
        if isinstance(payload, bytes):
            self.badges.print_process(f"Sending payload stage ({str(len(payload))} bytes)...")
        else:
            self.badges.print_process("Sending command payload stage...")

        self.post_tools.post_command(sender, payload, args)

    def open_session(self, host, port, session_platform, session_architecture, session_type, session, action=None):
        session_id = self.sessions.add_session(session_platform, session_architecture, session_type,
                                               host, port, session)
        time = datetime.datetime.now().astimezone().strftime("%Y-%m-%d %H:%M:%S %Z")

        self.badges.print_success(f"{session_type.title()} session {str(session_id)} opened at {time}!")

        if action:
            action()

        if self.local_storage.get("auto_interaction"):
            self.sessions.interact_with_session(session_id)

    def module_handle(self, host=None, sender=None, args={}, concat=None, location=None,
                      background=None, method=None, timeout=None, linemax=100, ensure=False,
                      on_session=None):
        module = self.modules.get_current_module_object()
        rhost = host

        options = module.handler
        payload = module.payload

        if 'BLINDER' in options:
            if options['BLINDER'].lower() in ['yes', 'y']:
                if sender is not None:
                    self.handle(
                        sender=sender,
                        args=args,
                        blinder=True
                    )

                    return True

        stage = payload['Payload'] if method != 'raw' else payload['Raw']

        if payload['Details']['Type'] == 'bind_tcp':
            host = options['RBHOST']
            port = options['RBPORT']

        elif payload['Details']['Type'] == 'reverse_tcp':
            host = options['LHOST']
            port = options['LPORT']

        else:
            host, port = None, None

        if 'Session' in payload['Details']:
            session = payload['Details']['Session']
        else:
            session = None

        if 'Arguments' in payload['Details']:
            arguments = payload['Details']['Arguments']
        else:
            arguments = None

        platform = payload['Details']['Platform']
        architecture = payload['Details']['Architecture']

        if platform in self.types.platforms:
            module_platform = module.details['Platform']

            if module_platform not in self.types.platforms:
                platform = module_platform

        return self.handle(
            payload=stage,
            sender=sender,

            host=host,
            port=port,

            rhost=rhost,

            payload_category=payload['Details']['Category'],
            payload_type=payload['Details']['Type'],

            args=args,
            concat=concat,
            location=location,
            background=background,

            method=method,
            timeout=timeout,
            linemax=linemax,

            platform=platform,
            architecture=architecture,

            ensure=ensure,
            blinder=False,

            session=session,
            arguments=arguments,
            on_session=on_session
        )

    def handle(self, payload=None, sender=None, host=None, port=None, rhost=None, payload_category='stager',
               payload_type='one_side', args={}, concat=None, location=None, background=None,
               method=None, timeout=None, linemax=100, platform='generic', architecture='generic',
               ensure=False, blinder=False, session=None, arguments=None, on_session=None):

        if blinder:
            self.blinder.shell(sender, args)
            return True

        if not self.send_payload(
            payload=payload,
            sender=sender,

            payload_category=payload_category,
            payload_type=payload_type,

            args=args,
            concat=concat,
            location=location,
            background=background,

            method=method,
            linemax=linemax,

            platform=platform,
            ensure=ensure,
            arguments=arguments
        ):
            self.badges.print_error("Failed to send payload stage!")
            return False

        remote = self.handle_session(
            host=host,
            port=port,

            payload_type=payload_type,
            session=session,
            timeout=timeout
        )

        if not remote:
            self.badges.print_warning("Payload sent but no session was opened.")
            return True

        session_type = remote[0].details['Type']

        remote[0].details['Post'] = method
        remote[0].details['Platform'] = platform
        remote[0].details['Architecture'] = architecture

        if remote[1] not in ('127.0.0.1', '0.0.0.0'):
            rhost = remote[1]

        self.open_session(rhost, port, platform, architecture, session_type, remote[0], on_session)
        return True

    def module_handle_session(self, payload_type='one_side', session=None, timeout=None):
        module = self.modules.get_current_module_object()

        options = module.handler
        session = session if session is not None else HatSploitSession

        if payload_type == 'reverse_tcp':
            new_session, host = self.server_handle.listen_session(
                options['LHOST'],
                options['LPORT'],
                session, timeout
            )

            if not new_session and not host:
                return None

        elif payload_type == 'bind_tcp':
            host = options['RBHOST']

            new_session = self.server_handle.connect_session(
                options['RBHOST'],
                options['RBPORT'],
                session, timeout
            )

            if not new_session:
                return None

        else:
            return None

        return new_session, host

    def handle_session(self, host=None, port=None, payload_type='one_side', session=None, timeout=None):
        session = session if session is not None else HatSploitSession

        if payload_type == 'reverse_tcp':
            if not host or not port:
                return None

            new_session, host = self.server_handle.listen_session(host, port, session, timeout)

            if not new_session and not host:
                return None

        elif payload_type == 'bind_tcp':
            if not host or not port:
                return None

            new_session = self.server_handle.connect_session(host, port, session, timeout)

            if not new_session:
                return None

        elif payload_type == 'one_side':
            return None

        else:
            self.badges.print_error("Invalid payload type!")
            return None

        return new_session, host

    def send_payload(self, payload=None, sender=None, payload_category='stager', payload_type='one_side',
                     args={}, concat=None, location=None, background=None, method=None, linemax=100,
                     platform='generic', ensure=False, arguments=None):
        if payload is None:
            self.badges.print_error("Payload stage is not found!")
            return False

        if sender is None:
            self.badges.print_error("No sender found!")
            return False

        if ensure:
            linemax = self.ensure_linemax(payload['Payload'], linemax)

        if payload_category == 'stager':
            self.badges.print_process(f"Sending payload stage ({str(len(payload))} bytes)...")

            if method != 'raw':
                self.do_job(
                    payload_type,
                    self.post.post,
                    [
                        platform,
                        sender,
                        payload,
                        args,
                        arguments,
                        method,
                        location,
                        concat,
                        background,
                        linemax
                    ]
                )

                return True

        if payload_category == 'singler' or method == 'raw':
            self.do_job(
                payload_type,
                self.send,
                [
                    sender,
                    payload,
                    args
                ]
            )

        else:
            self.badges.print_error("Invalid payload category!")
            return False

        return True
Beispiel #12
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()
Beispiel #13
0
class API:
    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)

    def run(self):
        cli.show_server_banner = lambda *_: None
        rest_api = Flask("HatSploit")

        log = logging.getLogger("werkzeug")
        log.setLevel(logging.ERROR)

        @rest_api.before_request
        def validate_token():
            if request.path not in ['/login', '/']:
                token = request.form['token']

                if token != self.token:
                    return make_response('', 401)

                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)

        @rest_api.route('/', methods=['GET', 'POST'])
        def api():
            version = self.config.core_config['details']['version']
            codename = self.config.core_config['details']['codename']

            response = "HatSploit REST API server\n"
            response += f"Version: {version}\n"

            if codename:
                response += f"Codename: {codename}\n"

            return make_response(f"<pre>{response}</pre>", 200)

        @rest_api.route('/login', methods=['POST'])
        def login_api():
            username = request.form['username']
            password = request.form['password']

            if username == self.username and password == self.password:
                return jsonify(token=self.token)
            return make_response('', 401)

        @rest_api.route('/execute', methods=['POST'])
        def commands_api():
            command = request.form['command']
            commands = self.fmt.format_commands(command)

            self.execute.execute_command(commands)

        @rest_api.route('/payloads', methods=['POST'])
        def payloads_api():
            action = None

            if 'action' in request.form:
                action = request.form['action']

            if action == 'list':
                data = {}
                all_payloads = self.payloads.get_payloads()
                number = 0

                for database in sorted(all_payloads):
                    payloads = all_payloads[database]

                    for payload in sorted(payloads):
                        data.update({
                            number: {
                                'Category': payloads[payload]['Category'],
                                'Payload': payloads[payload]['Payload'],
                                'Rank': payloads[payload]['Rank'],
                                'Name': payloads[payload]['Name'],
                                'Platform': payloads[payload]['Platform']
                            }
                        })

                        number += 1

                return jsonify(data)
            return make_response('', 200)

        @rest_api.route('/modules', methods=['POST'])
        def modules_api():
            action = None

            if 'action' in request.form:
                action = request.form['action']

            if action == 'list':
                data = {}
                all_modules = self.modules.get_modules()
                number = 0

                for database in sorted(all_modules):
                    modules = all_modules[database]

                    for module in sorted(modules):
                        data.update({
                            number: {
                                'Category': modules[module]['Category'],
                                'Module': modules[module]['Module'],
                                'Rank': modules[module]['Rank'],
                                'Name': modules[module]['Name'],
                                'Platform': modules[module]['Platform']
                            }
                        })

                        number += 1

                return jsonify(data)

            if action == 'options':
                data = {}
                current_module = self.modules.get_current_module_object()

                if current_module:
                    options = current_module.options

                    for option in sorted(options):
                        value, required = options[option]['Value'], options[
                            option]['Required']
                        if required:
                            required = 'yes'
                        else:
                            required = 'no'
                        if not value and value != 0:
                            value = ""
                        data.update({
                            option: {
                                'Value': value,
                                'Required': required,
                                'Description': options[option]['Description']
                            }
                        })

                    if hasattr(current_module, "payload"):
                        current_payload = self.payloads.get_current_payload()

                        if hasattr(current_payload, "options"):
                            options = current_payload.options

                            for option in sorted(options):
                                value, required = options[option][
                                    'Value'], options[option]['Required']
                                if required:
                                    required = 'yes'
                                else:
                                    required = 'no'
                                if not value and value != 0:
                                    value = ""
                                data.update({
                                    option: {
                                        'Value':
                                        value,
                                        'Required':
                                        required,
                                        'Description':
                                        options[option]['Description']
                                    }
                                })

                return jsonify(data)

            if action == 'use':
                self.modules.use_module(request.form['module'])

            if action == 'set':
                self.modules.set_current_module_option(request.form['option'],
                                                       request.form['value'])

            if action == 'run':
                current_module = self.modules.get_current_module_object()

                if current_module:
                    self.jobs.create_job(current_module.details['Name'],
                                         current_module.details['Module'],
                                         self.modules.run_current_module)

            return make_response('', 200)

        @rest_api.route('/sessions', methods=['POST'])
        def sessions_api():
            action = None

            if 'action' in request.form:
                action = request.form['action']

            if action == 'close':
                session = request.form['session']
                self.sessions.close_session(session)

            elif action == 'list':
                data = {}
                sessions = self.sessions.get_all_sessions()
                fetch = 'all'

                if 'fetch' in request.form:
                    fetch = request.form['fetch']

                if sessions:
                    for session in sessions:
                        if fetch == 'all':
                            data.update({
                                session: {
                                    'platform':
                                    sessions[session]['platform'],
                                    'architecture':
                                    sessions[session]['architecture'],
                                    'type':
                                    sessions[session]['type'],
                                    'host':
                                    sessions[session]['host'],
                                    'port':
                                    sessions[session]['port']
                                }
                            })
                        elif fetch == sessions[session]['platform']:
                            data.update({
                                session: {
                                    'platform':
                                    sessions[session]['platform'],
                                    'architecture':
                                    sessions[session]['architecture'],
                                    'type':
                                    sessions[session]['type'],
                                    'host':
                                    sessions[session]['host'],
                                    'port':
                                    sessions[session]['port']
                                }
                            })

                return jsonify(data)

            elif action == 'execute':
                session = request.form['session']
                session = self.sessions.get_session(session)

                if session:
                    if request.form['output'].lower() in ['yes', 'y']:
                        output = session.send_command(request.form['command'],
                                                      output=True)
                        return jsonify(output=output)

                    session.send_command(request.form['command'])

            elif action == 'download':
                if 'local_path' in request.form:
                    local_path = request.form['local_path']
                else:
                    local_path = self.config.path_config['loot_path']

                self.sessions.session_download(request.form['session'],
                                               request.form['remote_file'],
                                               local_path)

            elif action == 'upload':
                self.session.session_upload(request.form['session'],
                                            request.form['local_file'],
                                            request.form['remote_path'])

            return make_response('', 200)

        rest_api.run(host=self.host, port=self.port)
Beispiel #14
0
class Jobs:
    exceptions = Exceptions()
    tables = Tables()
    badges = Badges()
    local_storage = LocalStorage()
    modules = Modules()

    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)

        hidden_jobs = self.local_storage.get("hidden_jobs")
        if hidden_jobs:
            for job_id in list(hidden_jobs):
                if not hidden_jobs[job_id]['job_process'].is_alive():
                    self.delete_job(job_id, True)

    def count_jobs(self):
        jobs = self.local_storage.get("jobs")
        if jobs:
            return len(jobs)
        return 0

    def exit_jobs(self):
        if not self.local_storage.get("jobs"):
            if self.local_storage.get("hidden_jobs"):
                self.stop_all_jobs()
            return True

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

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

        hidden_jobs = self.local_storage.get("hidden_jobs")
        if hidden_jobs:
            for job_id in list(hidden_jobs):
                self.delete_job(job_id, True)

    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, hidden=False):
        jobs_var = "jobs"
        if hidden:
            jobs_var = "hidden_jobs"

        if self.local_storage.get(jobs_var):
            job_id = int(job_id)
            if job_id in list(self.local_storage.get(jobs_var)):
                try:
                    self.stop_job(
                        self.local_storage.get(jobs_var)[job_id]
                        ['job_process'])
                    self.local_storage.delete_element(jobs_var, job_id)
                except Exception:
                    self.badges.print_error("Failed to stop job!")
            else:
                self.badges.print_error("Invalid job given!")
        else:
            self.badges.print_error("Invalid job given!")

    def create_job(self,
                   job_name,
                   module_name,
                   job_function,
                   job_arguments=[],
                   hidden=False):
        jobs_var = "jobs"
        if hidden:
            jobs_var = "hidden_jobs"

        self.start_job(job_function, job_arguments)
        if not self.local_storage.get(jobs_var):
            self.local_storage.set(jobs_var, {})
        job_id = len(self.local_storage.get(jobs_var))

        job_data = {
            job_id: {
                'job_name': job_name,
                'module_name': module_name,
                'job_process': self.job_process
            }
        }
        self.local_storage.update(jobs_var, job_data)
Beispiel #15
0
class Show:
    jobs = Jobs()
    loot = Loot()
    local_storage = LocalStorage()
    modules = Modules()
    payloads = Payloads()
    sessions = Sessions()

    colors = Colors()
    badges = Badges()
    tables = Tables()

    def show_custom_commands(self, handler):
        commands_data = {}
        headers = ("Command", "Description")
        commands = handler

        for command in sorted(commands):
            label = commands[command].details['Category']
            commands_data[label] = []
        for command in sorted(commands):
            label = commands[command].details['Category']
            commands_data[label].append(
                (command, commands[command].details['Description']))
        for label in sorted(commands_data):
            self.tables.print_table(label.title() + " Commands", headers,
                                    *commands_data[label])

    def show_interface_commands(self):
        if self.local_storage.get("commands"):
            self.show_custom_commands(self.local_storage.get("commands"))
        else:
            self.badges.print_warning("No commands available.")

    def show_plugin_commands(self):
        for plugin in self.local_storage.get("loaded_plugins"):
            loaded_plugin = self.local_storage.get("loaded_plugins")[plugin]
            if hasattr(loaded_plugin, "commands"):
                commands_data = {}
                headers = ("Command", "Description")
                commands = loaded_plugin.commands
                for label in sorted(commands):
                    commands_data[label] = []
                    for command in sorted(commands[label]):
                        commands_data[label].append(
                            (command, commands[label][command]['Description']))
                for label in sorted(commands_data):
                    self.tables.print_table(label.title() + " Commands",
                                            headers, *commands_data[label])

    def show_module_commands(self):
        current_module = self.modules.get_current_module_object()
        if hasattr(current_module, "commands"):
            commands_data = []
            headers = ("Command", "Description")
            commands = current_module.commands
            for command in sorted(commands):
                commands_data.append(
                    (command, commands[command]['Description']))
            self.tables.print_table("Module Commands", headers, *commands_data)

    def show_all_commands(self):
        self.show_interface_commands()
        if self.modules.check_current_module():
            self.show_module_commands()
        if self.local_storage.get("loaded_plugins"):
            self.show_plugin_commands()

    def show_jobs(self):
        if self.local_storage.get("jobs"):
            jobs_data = []
            headers = ("ID", "Name", "Module")
            jobs = self.local_storage.get("jobs")
            for job_id in jobs:
                jobs_data.append((job_id, jobs[job_id]['job_name'],
                                  jobs[job_id]['module_name']))
            self.tables.print_table("Active Jobs", headers, *jobs_data)
        else:
            self.badges.print_warning("No running jobs available.")

    def show_loot(self):
        loots = self.loot.list_loot()
        if loots:
            headers = ("Loot", "Path", "Time")
            self.tables.print_table("Collected Loot", headers, *loots)
        else:
            self.badges.print_warning("No loot collected yet.")

    def show_module_databases(self):
        if self.local_storage.get("connected_module_databases"):
            databases_data = []
            number = 0
            headers = ("Number", "Name", "Path")
            databases = self.local_storage.get("connected_module_databases")

            for name in databases:
                databases_data.append((number, name, databases[name]['path']))
                number += 1
            self.tables.print_table("Connected Module Databases", headers,
                                    *databases_data)
        else:
            self.badges.print_warning("No module database connected.")

    def show_payload_databases(self):
        if self.local_storage.get("connected_payload_databases"):
            databases_data = []
            number = 0
            headers = ("Number", "Name", "Path")
            databases = self.local_storage.get("connected_payload_databases")

            for name in databases:
                databases_data.append((number, name, databases[name]['path']))
                number += 1
            self.tables.print_table("Connected Payload Databases", headers,
                                    *databases_data)
        else:
            self.badges.print_warning("No payload database connected.")

    def show_plugin_databases(self):
        if self.local_storage.get("connected_plugin_databases"):
            databases_data = []
            number = 0
            headers = ("Number", "Name", "Path")
            databases = self.local_storage.get("connected_plugin_databases")

            for name in databases:
                databases_data.append((number, name, databases[name]['path']))
                number += 1
            self.tables.print_table("Connected Plugin Databases", headers,
                                    *databases_data)
        else:
            self.badges.print_warning("No plugin database connected.")

    def show_plugins(self):
        all_plugins = self.local_storage.get("plugins")
        headers = ("Number", "Plugin", "Name")
        plugins_shorts = {}

        for database in sorted(all_plugins):
            number = 0
            plugins_data = []
            plugins = all_plugins[database]

            for plugin in sorted(plugins):
                plugins_data.append((number, plugins[plugin]['Plugin'],
                                     plugins[plugin]['Name']))
                plugins_shorts.update({number: plugins[plugin]['Plugin']})
                number += 1

            self.tables.print_table(f"Plugins ({database})", headers,
                                    *plugins_data)
            self.local_storage.set("plugin_shorts", plugins_shorts)

    def show_modules(self, category=None):
        all_modules = self.local_storage.get("modules")
        headers = ("Number", "Category", "Module", "Rank", "Name")
        modules_shorts = {}

        for database in sorted(all_modules):
            number = 0
            modules_data = []
            modules = all_modules[database]

            for module in sorted(modules):
                if category:
                    if category == modules[module]['Category']:
                        modules_data.append(
                            (number, modules[module]['Category'],
                             modules[module]['Module'],
                             modules[module]['Rank'], modules[module]['Name']))
                        modules_shorts.update(
                            {number: modules[module]['Module']})
                        number += 1
                else:
                    modules_data.append(
                        (number, modules[module]['Category'],
                         modules[module]['Module'], modules[module]['Rank'],
                         modules[module]['Name']))
                    modules_shorts.update({number: modules[module]['Module']})
                    number += 1

            if category:
                self.tables.print_table(
                    f"{category.title()} Modules ({database})", headers,
                    *modules_data)
            else:
                self.tables.print_table(f"Modules ({database})", headers,
                                        *modules_data)

            self.local_storage.set("module_shorts", modules_shorts)

    def show_payloads(self, category=None):
        all_payloads = self.local_storage.get("payloads")
        headers = ("Number", "Category", "Payload", "Rank", "Name")
        payloads_shorts = {}

        for database in sorted(all_payloads):
            number = 0
            payloads_data = []
            payloads = all_payloads[database]

            for payload in sorted(payloads):
                if category:
                    if category == payloads[payload]['Category']:
                        payloads_data.append(
                            (number, payloads[payload]['Category'],
                             payloads[payload]['Payload'],
                             payloads[payload]['Rank'],
                             payloads[payload]['Name']))
                        payloads_shorts.update(
                            {number: payloads[payload]['Payload']})
                        number += 1
                else:
                    payloads_data.append(
                        (number, payloads[payload]['Category'],
                         payloads[payload]['Payload'],
                         payloads[payload]['Rank'], payloads[payload]['Name']))
                    payloads_shorts.update(
                        {number: payloads[payload]['Payload']})
                    number += 1

            if category:
                self.tables.print_table(
                    f"{category.title()} Payloads ({database})", headers,
                    *payloads_data)
            else:
                self.tables.print_table(f"Payloads ({database})", headers,
                                        *payloads_data)

            self.local_storage.set("payload_shorts", payloads_shorts)

    def show_search_plugins(self, keyword):
        all_plugins = self.local_storage.get("plugins")
        plugins_shorts = {}

        if all_plugins:
            headers = ("Number", "Plugin", "Name")
            for database in all_plugins:
                number = 0
                plugins_data = []
                plugins = all_plugins[database]

                for plugin in sorted(plugins):
                    if keyword in plugins[plugin][
                            'Plugin'] or keyword in plugins[plugin]['Name']:
                        name = plugins[plugin]['Plugin'].replace(
                            keyword,
                            self.colors.RED + keyword + self.colors.END)
                        description = plugins[plugin]['Name'].replace(
                            keyword,
                            self.colors.RED + keyword + self.colors.END)

                        plugins_data.append((number, name, description))
                        plugins_shorts.update(
                            {number: plugins[plugin]['Plugin']})

                        number += 1
                if plugins_data:
                    self.tables.print_table(f"Plugins ({database})", headers,
                                            *plugins_data)
                    self.local_storage.set("plugin_shorts", plugins_shorts)

    def show_search_modules(self, keyword):
        all_modules = self.local_storage.get("modules")
        modules_shorts = {}

        if all_modules:
            headers = ("Number", "Module", "Rank", "Name")
            for database in all_modules:
                number = 0
                modules_data = []
                modules = all_modules[database]

                for module in sorted(modules):
                    if keyword in modules[module][
                            'Module'] or keyword in modules[module]['Name']:
                        name = modules[module]['Module'].replace(
                            keyword,
                            self.colors.RED + keyword + self.colors.END)
                        description = modules[module]['Name'].replace(
                            keyword,
                            self.colors.RED + keyword + self.colors.END)

                        modules_data.append(
                            (number, name, modules[module]['Rank'],
                             description))
                        modules_shorts.update(
                            {number: modules[module]['Module']})

                        number += 1
                if modules_data:
                    self.tables.print_table(f"Modules ({database})", headers,
                                            *modules_data)
                    self.local_storage.set("module_shorts", modules_shorts)

    def show_search_payloads(self, keyword):
        all_payloads = self.local_storage.get("payloads")
        payloads_shorts = {}

        if all_payloads:
            headers = ("Number", "Category", "Payload", "Rank", "Name")
            for database in all_payloads:
                number = 0
                payloads_data = []
                payloads = all_payloads[database]

                for payload in sorted(payloads):
                    if keyword in payloads[payload][
                            'Payload'] or keyword in payloads[payload]['Name']:
                        name = payloads[payload]['Payload'].replace(
                            keyword,
                            self.colors.RED + keyword + self.colors.END)
                        description = payloads[payload]['Name'].replace(
                            keyword,
                            self.colors.RED + keyword + self.colors.END)

                        payloads_data.append(
                            (number, payloads[payload]['Category'], name,
                             payloads[payload]['Rank'], description))
                        payloads_shorts.update(
                            {number: payloads[payload]['Payload']})

                        number += 1
                if payloads_data:
                    self.tables.print_table(f"Payloads ({database})", headers,
                                            *payloads_data)
                    self.local_storage.set("payload_shorts", payloads_shorts)

    def show_sessions(self):
        sessions = self.local_storage.get("sessions")
        if sessions:
            sessions_data = []
            headers = ("ID", "Platform", "Architecture", "Type", "Host",
                       "Port")
            for session_id in sessions:
                session_platform = sessions[session_id]['platform']
                session_architecture = sessions[session_id]['architecture']
                session_type = sessions[session_id]['type']
                host = sessions[session_id]['host']
                port = sessions[session_id]['port']

                sessions_data.append(
                    (session_id, session_platform, session_architecture,
                     session_type, host, port))
            self.tables.print_table("Opened Sessions", headers, *sessions_data)
        else:
            self.badges.print_warning("No opened sessions available.")

    def show_module_information(self, current_module_details):
        current_module = current_module_details

        authors = ""
        for author in current_module['Authors']:
            authors += author + ", "
        authors = authors[:-2]

        self.badges.print_information("Module information:")
        self.badges.print_empty("")

        if current_module['Name']:
            self.badges.print_empty("         Name: " + current_module['Name'])
        if current_module['Module']:
            self.badges.print_empty("       Module: " +
                                    current_module['Module'])
        if authors:
            self.badges.print_empty("      Authors: ")
            for author in current_module['Authors']:
                self.badges.print_empty("               " + author)
        if current_module['Description']:
            self.badges.print_empty("  Description: " +
                                    current_module['Description'])
        if current_module['Rank']:
            self.badges.print_empty("         Rank: " + current_module['Rank'])

        self.badges.print_empty("")

    def show_options(self):
        current_module = self.modules.get_current_module_object()

        if not current_module:
            self.badges.print_warning("No module selected.")
            return

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

        if not hasattr(current_module, "options") and not hasattr(
                self.payloads.get_current_payload(), "options"):
            self.badges.print_warning("Module has no options.")
            return

        if hasattr(current_module, "options"):
            options_data = []
            headers = ("Option", "Value", "Required", "Description")
            options = current_module.options

            for option in sorted(options):
                value, required = options[option]['Value'], options[option][
                    'Required']
                if required:
                    required = "yes"
                else:
                    required = "no"
                if not value and value != 0:
                    value = ""
                options_data.append(
                    (option, value, required, options[option]['Description']))
            self.tables.print_table(
                f"Module Options ({current_module.details['Module']})",
                headers, *options_data)

        if hasattr(current_module, "payload"):
            if hasattr(self.payloads.get_current_payload(), "options"):
                options_data = []
                headers = ("Option", "Value", "Required", "Description")
                current_payload = self.payloads.get_current_payload()
                if current_payload:
                    for option in sorted(current_payload.options):
                        value, required = current_payload.options[option]['Value'], \
                                          current_payload.options[option]['Required']
                        if required:
                            required = "yes"
                        else:
                            required = "no"
                        if not value and value != 0:
                            value = ""
                        options_data.append(
                            (option, value, required,
                             current_payload.options[option]['Description']))
                    self.tables.print_table(
                        f"Payload Options ({current_payload.details['Payload']})",
                        headers, *options_data)